﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


public static class SettingHelper
{
    public static readonly string cache_site = "CACHE_SETTING_SITE";
    public static readonly string cache_all = "CACHE_SETTING_ALL";
    public static string ReadJsonFile(this string file)
    {
        using (StreamReader sr = new StreamReader(file, Encoding.Default))
        {
            string json = sr.ReadToEnd();
            return json;
        }
    }

    public static Dictionary<string, object> Json2Dictionary(this string json)
    {
        try
        {
            JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
            Dictionary<string, object> ret = new Dictionary<string, object>();
            foreach (var p in jsonObj.Properties().ToArray()) ret.Add(p.Name, p.Value.ToString());
            return ret;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public static List<Dictionary<string, object>> Json2List(this string json)
    {
        try
        {
            JArray jsonObj = JsonConvert.DeserializeObject(json) as JArray;
            List<Dictionary<string, object>> ret = new List<Dictionary<string, object>>();
            foreach (var item in jsonObj)
            {
                Dictionary<string, object> dict = item.ToString().Json2Dictionary();
                ret.Add(dict);
            }
            return ret;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public static string ReadSiteSetting()
    {
        object json = Cacheing.Get(cache_all);
        if (json == null)
        {
            string settingFile = HttpContext.Current.Server.MapPath("/App_Data/settings.json");
            json = settingFile.ReadJsonFile();
            Cacheing.Add(cache_all, json.ToString(), 3600);
        }
        return json.ToString();
    }
    public static Dictionary<string, object> GetSiteSetting()
    {
        object site = Cacheing.Get(cache_site);
        if (site == null)
        {
            string json = SettingHelper.ReadSiteSetting();
            if (string.IsNullOrWhiteSpace(json)) return null;
            Dictionary<string, object> dict = json.Json2Dictionary();
            if (dict == null || !dict.Keys.Contains("site")) return null;
            dict = dict["site"].ToString().Json2Dictionary();
            Cacheing.Add(cache_site, dict, 3600);
            return dict;
        }
        else return (Dictionary<string, object>)site;
    }
}
